/**
 * 权限同步Hook
 * 用于实现权限变更的实时生效机制
 */

import { useEffect, useCallback, useRef } from 'react';
import { useAuth } from '../contexts/AuthContext';
import { permissionWatcher } from '../services/permissionWatcher';
import { menuService } from '../services/menuService';

interface UsePermissionSyncOptions {
  /**
   * 权限变更时的回调函数
   */
  onPermissionChange?: (permissions: string[]) => void;
  
  /**
   * 是否自动刷新菜单
   */
  autoRefreshMenu?: boolean;
  
  /**
   * 是否启用调试日志
   */
  debug?: boolean;
}

/**
 * 权限同步Hook
 */
export const usePermissionSync = (options: UsePermissionSyncOptions = {}) => {
  const { 
    onPermissionChange, 
    autoRefreshMenu = true, 
    debug = false 
  } = options;
  
  const { state, hasPermission } = useAuth();
  const callbackRef = useRef(onPermissionChange);
  const debugRef = useRef(debug);

  // 更新回调引用
  useEffect(() => {
    callbackRef.current = onPermissionChange;
    debugRef.current = debug;
  }, [onPermissionChange, debug]);

  /**
   * 处理权限变更
   */
  const handlePermissionChange = useCallback(async (newPermissions: string[]) => {
    if (debugRef.current) {
      console.log('🔄 权限变更检测:', {
        oldCount: permissionWatcher.getCurrentPermissions().length,
        newCount: newPermissions.length,
        newPermissions
      });
    }

    try {
      // 自动刷新菜单
      if (autoRefreshMenu) {
        if (debugRef.current) {
          console.log('🔄 自动刷新菜单...');
        }
        await menuService.refreshMenuWithPermissions(hasPermission);
      }

      // 调用用户自定义回调
      if (callbackRef.current) {
        callbackRef.current(newPermissions);
      }

      if (debugRef.current) {
        console.log('✅ 权限同步完成');
      }
    } catch (error) {
      console.error('❌ 权限同步失败:', error);
    }
  }, [hasPermission, autoRefreshMenu]);

  /**
   * 手动触发权限检查
   */
  const checkPermissions = useCallback(async () => {
    if (debugRef.current) {
      console.log('🔍 手动检查权限...');
    }
    await permissionWatcher.checkPermissionChanges();
  }, []);

  /**
   * 立即更新权限
   */
  const updatePermissions = useCallback((newPermissions: string[]) => {
    if (debugRef.current) {
      console.log('⚡ 立即更新权限:', newPermissions);
    }
    permissionWatcher.updatePermissions(newPermissions);
  }, []);

  // 注册权限变更监听器
  useEffect(() => {
    if (!state.isAuthenticated) {
      return;
    }

    if (debugRef.current) {
      console.log('🎯 注册权限变更监听器');
    }

    const unsubscribe = permissionWatcher.onPermissionChange(handlePermissionChange);

    return () => {
      if (debugRef.current) {
        console.log('🔌 取消权限变更监听器');
      }
      unsubscribe();
    };
  }, [state.isAuthenticated, handlePermissionChange]);

  return {
    /**
     * 当前权限列表
     */
    currentPermissions: permissionWatcher.getCurrentPermissions(),
    
    /**
     * 手动检查权限变更
     */
    checkPermissions,
    
    /**
     * 立即更新权限
     */
    updatePermissions,
    
    /**
     * 是否已认证
     */
    isAuthenticated: state.isAuthenticated
  };
};

export default usePermissionSync;
